<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:include="include :: header"></head>
<style>


    table tr th, table tr td {
        border-color: #000000;
        text-align: center;
        vertical-align: middle;
        font-size: 16px;
        line-height: 30px;
        border: #000000 1px solid;
    }

    table tr td input {
        border: none;
        width: 100%;
        height: 30px;
        outline: none;
        text-align: center;
    }

    table tr td textarea {
        border: none;
        width: 100%;
        height: 30px;
        outline: none;
        resize: none;

    }

    .changeCursorIco {
        cursor: pointer !important;
    }
</style>
<body class="hold-transition skin-yellow sidebar-mini"
      style="background:url('/img/worker01.png') no-repeat;background-size:90px 168px; background-position: 99% 100%">
<section class="content-header">
    <h1>生产计划编辑</h1>
</section>
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box" style="box-shadow:none">
                <div class="box-body">
                    <div class="col-md-12">
                        <form id="dataForm">
                            <table id="formTable" width="100%" border="0" cellpadding="0" cellspacing="0"
                                   style="margin-left: 10px">
                                <tr id="tableTitle1">
                                    <td colspan="14"
                                        style="font-size: 20px;height: 35px">
                                        <B>生产计划编辑</B>
                                    </td>
                                    <td style="border:none">
                                    </td>
                                </tr>
                                <tr id="prodInfo">
                                    <td style="width: 160px;">项目编号</td>
                                    <td style="width:160px;">
                                        <select id="profProdNo" class="select2"
                                                style="width: 100%;height:29px;border:none;outline: none;text-align: center;text-align-last: center;">

                                        </select>
                                    </td>
                                    <td style="width:160px;">项目名称</td>
                                    <td colspan="3" id="proName"></td>
                                    <td style="width:80px;">项目数量</td>
                                    <td id="prodNum" style="width:80px;"></td>
                                    <td style="width:80px;">类别</td>
                                    <td id="prodTyp" style="width:80px;"></td>
                                    <td style="width:80px;">是否重点</td>
                                    <td id="prodIsKey" style="width:40px;"></td>
                                    <td style="width:80px;">交货日期</td>
                                    <td id="prodDelDat" style="width:100px;"></td>
                                    <td style="border:none">
                                    </td>
                                </tr>
                                <tr id="tableTitle3">
                                    <td>序号</td>
                                    <td>分配车间/组/人员</td>
                                    <td>工作</td>
                                    <td>开始时间</td>
                                    <td>结束时间</td>
                                    <td>历时（天）</td>
                                    <td colspan="8">备注</td>
                                    <td name="oper" style="border:none;width:60px;">
                                        <button type="button" class="pull-left" onclick="addRow(this)"
                                                style="border:none;background:transparent;color:green;font-size: 18px">
                                            <i class="fa fa-plus"></i></button>
                                        <!--                                            <button onclick="subtractRow()"-->
                                        <!--                                                    style="border:none;background:transparent;color:red;font-size: 18px">-->
                                        <!--                                                <i class="fa fa-close"></i></button>-->
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </div>
                    <div class="col-md-12" style="margin-top:10px; ">
                        <button id="btn_cancel" class="btn btn-default pull-right"
                                style="margin-right: 5px;width: 82px;"
                                onclick="cancel()" type="button">取消
                        </button>
                        <button id="btn_save" class="btn btn-success pull-right" style="margin-right: 5px;width: 82px;" shiro:authenticated="pro:productPlan:edit"
                                onclick="save()" shiro:hasPermission="pro:productPlan:edit" type="button">保存
                        </button>

                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<div th:include="include :: footer"></div>
<script th:inline="javascript">
    let currentProdNo;
    /**
     * Jquery 就绪函数
     */
    $(function () {
        //加载生产令数据列表
        loadProdList();
        /**
         * 下拉菜单改变事件
         */
        $("#profProdNo").change(function () {
            currentProdNo = $("#profProdNo").val();
            js.post({
                url: ctx + 'task/factoryPlanEditAndReturn/loadProdList',
                type: 'post',
                traditional: true,            // 阻止深度序列化， 使参数可以使用数组
                dataType: 'json',
                contentType: "application/x-www-form-urlencoded",
                data: {},
                async: true,                // 异步执行
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        $("#profProdNo").empty();
                        let list = result.data;
                        let selectOptionArray = new Array();
                        selectOptionArray.push('<option style="text-align: center" value="">---请选择---</option>');
                        let selected = '';
                        for (let i = 0; i < list.length; i++) {
                            if (list[i].prodNo === currentProdNo) {
                                selected = 'selected="selected"';
                                $("[name='profProdNo']").val(currentProdNo);
                                if (list[i].proName != undefined && list[i].proName != null) {
                                    $("#proName").html(list[i].proName);
                                } else {
                                    $("#proName").html("");
                                }
                                if (list[i].prodNum != undefined && list[i].prodNum != null) {
                                    $("#prodNum").html(list[i].prodNum);
                                } else {
                                    $("#prodNum").html("");
                                }
                                if (list[i].prodTyp === 1) {
                                    $("#prodTyp").html("设备类");
                                } else if (list[i].prodTyp === 2) {
                                    $("#prodTyp").html("其他类");
                                } else {
                                    $("#prodTyp").html("");
                                }
                                if (list[i].prodIsKey === 1) {
                                    $("#prodIsKey").html("是");
                                } else if (list[i].prodIsKey === 0) {
                                    $("#prodIsKey").html("否");
                                } else {
                                    $("#prodIsKey").html("");
                                }
                                if (list[i].prodDelDat != undefined && list[i].prodDelDat != null) {
                                    $("#prodDelDat").html(list[i].prodDelDat);
                                } else {
                                    $("#prodDelDat").html("");
                                }
                            } else {
                                selected = '';
                            }
                            selectOptionArray.push('<option ' + selected + ' style="text-align: center" value="' + list[i].prodNo + '">' + list[i].prodNo + '</option>');
                        }
                        $("#profProdNo").html(selectOptionArray.join(''));
                    }
                },
                error: function () {
                    js.modal.fail();
                }
            });
        })
    });

    /**
     * 加载生产令数据列表
     */
    function loadProdList() {
        js.post({
            url: ctx + 'task/factoryPlanEditAndReturn/loadProdList',
            type: 'post',
            traditional: true,            // 阻止深度序列化， 使参数可以使用数组
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            data: {},
            async: true,                // 异步执行
            success: function (result) {
                if (result.type === web_status.SUCCESS) {
                    $("#profProdNo").empty();
                    let list = result.data;
                    let selectOptionArray = new Array();
                    selectOptionArray.push('<option style="text-align: center" value="">---请选择---</option>');
                    for (let i = 0; i < list.length; i++) {
                        selectOptionArray.push('<option style="text-align: center" value="' + list[i].prodNo + '">' + list[i].prodNo + '</option>');
                    }
                    $("#profProdNo").html(selectOptionArray.join(''));
                }
            },
            error: function () {
                js.modal.fail();
            }
        });
    }

    /**
     * 添加新行
     */
    function addRow(obj) {
        let tdEl = new Array();
        let newOrderNo = getNewOrderNo();
        tdEl.push('<td name="orderNo">' + newOrderNo + '</td>');
        tdEl.push('<td><input class="form-control" name="profFacWor" type="text" style="outline：none;" placeholder="请输入车间/组/人员"/><input class="form-control" name="profProdNo" type="hidden" style="display:none" value="' + $("#profProdNo").val() + '" /></td>');
        tdEl.push('<td><input class="form-control" name="profName" type="text" style="outline：none;" placeholder="请输入工作任务"/></td>');
        tdEl.push('<td><input class="form-control changeCursorIco" onchange="verificationStart(this)" name="profStaDat" type="text" style="outline：none;" readOnly="readonly" alt="点击选择开始时间"/></td>');
        tdEl.push('<td><input class="form-control changeCursorIco" onchange="verificationEnd(this)" name="profEndDat" type="text" style="outline：none;" readOnly="readonly" alt="点击选择结束时间"/></td>');
        tdEl.push('<td><input class="form-control" name="duration" type="text" style="outline：none;" readOnly="readonly"/></td>');
        tdEl.push('<td colspan="8"><textarea class="form-control" name="profRem" type="text" maxlength="255" style="outline：none;border: none;width: 100%;height: 30px;outline: none;resize: none;"></textarea></td>');
        tdEl.push('<td name="oper" style="border:none;width:60px;"><button type="button" class="pull-left" onclick="addRow(this)" style="border:none;background:transparent;color:green;font-size: 18px"><i class="fa fa-plus"></i></button><button onclick="subtractRow(this)" style="border:none;background:transparent;color:red;font-size: 18px"> <i class="fa fa-close"></i></button></td>');
        $(obj).parent().parent().after('<tr id="dataRow_' + newOrderNo + '">' + tdEl + '</tr>')
        $("#formTable [name='profStaDat']").datepicker({
            format: "yyyy-mm-dd",
            language: "zh-cn",
            autoclose: true,
            todayHighlight: true,
            clearBtn: true
        });
        $("#formTable [name='profEndDat']").datepicker({
            format: "yyyy-mm-dd",
            language: "zh-cn",
            autoclose: true,
            todayHighlight: true,
            clearBtn: true
        });
        $(obj).parent().html('');
    }

    /**
     * 移除本行
     */
    function subtractRow(obj) {
        $(obj).parent().parent().remove();
        let lastId = $('#formTable tr:last').attr('id');
        if (lastId === 'tableTitle3') {
            $('#formTable tr:last').find("[name='oper']").html('<button type="button" class="pull-left" onclick="addRow(this)" style="border:none;background:transparent;color:green;font-size: 18px"><i class="fa fa-plus"></i></button>');
        } else {
            $('#formTable tr:last').find("[name='oper']").html('<button type="button" class="pull-left" onclick="addRow(this)" style="border:none;background:transparent;color:green;font-size: 18px"><i class="fa fa-plus"></i></button><button onclick="subtractRow(this)" style="border:none;background:transparent;color:red;font-size: 18px"> <i class="fa fa-close"></i></button>');
        }
        //重新排序
        let index = 1;
        $("#formTable tr [name='orderNo']").each(function () {
            $(this).html(index);
            index++;
        });
    }

    /**
     * 获取最新行号
     */
    function getNewOrderNo() {
        let rowIndex = 1;
        $("#formTable tr").each(function () {
            let idText = $(this).attr("id");
            if (idText.indexOf("dataRow") > -1) {
                rowIndex++;
            }
        });
        return rowIndex;
    }

    /**
     * 验证当结束时间是否大于开始时间
     */
    function verificationStart(obj) {
        let startVal = $(obj).val();
        let endVal = $(obj).parent().parent().find("[name='profEndDat']").val();
        if (startVal != undefined && endVal != undefined) {
            let start = new Date(startVal);
            let end = new Date(endVal);
            if (end <= start) {
                $(obj).val('');
                js.modal.warning("尊敬的用户，您所输入的开始时间必须大于结束时间！");
            } else if ($(obj).parent().parent().find("[name='profStaDat']").val() != undefined &&
                $(obj).parent().parent().find("[name='profStaDat']").val() != null &&
                $(obj).parent().parent().find("[name='profStaDat']").val() != '' &&
                $(obj).parent().parent().find("[name='profEndDat']").val() != undefined &&
                $(obj).parent().parent().find("[name='profEndDat']").val() != null &&
                $(obj).parent().parent().find("[name='profEndDat']").val() != '') {
                let duration = $(obj).parent().parent().find("[name='duration']");
                let profStaDat = new Date($(obj).parent().parent().find("[name='profStaDat']").val());
                let profEndDat = new Date($(obj).parent().parent().find("[name='profEndDat']").val());
                duration.val(Math.floor((profEndDat - profStaDat) / 1000 / 60 / 60 / 24));
            }
        }
    }

    /**
     * 验证当结束时间是否大于开始时间
     */
    function verificationEnd(obj) {
        let endVal = $(obj).val();
        let startVal = $(obj).parent().parent().find("[name='profStaDat']").val();
        if (startVal != undefined && endVal != undefined) {
            let end = new Date($(obj).val());
            let start = new Date($(obj).parent().parent().find("[name='profStaDat']").val());
            if (end <= start) {
                $(obj).val('');
                js.modal.warning("尊敬的用户，您所输入的结束时间必须大于开始时间！");
            } else if ($(obj).parent().parent().find("[name='profStaDat']").val() != undefined &&
                $(obj).parent().parent().find("[name='profStaDat']").val() != null &&
                $(obj).parent().parent().find("[name='profStaDat']").val() != '' &&
                $(obj).parent().parent().find("[name='profEndDat']").val() != undefined &&
                $(obj).parent().parent().find("[name='profEndDat']").val() != null &&
                $(obj).parent().parent().find("[name='profEndDat']").val() != '') {
                let duration = $(obj).parent().parent().find("[name='duration']");
                let profStaDat = new Date($(obj).parent().parent().find("[name='profStaDat']").val());
                let profEndDat = new Date($(obj).parent().parent().find("[name='profEndDat']").val());
                duration.val(Math.floor((profEndDat - profStaDat) / 1000 / 60 / 60 / 24));
            }
        }
    }

    /**
     * 保存
     * @param obj
     */
    function save(obj) {
        let dataArray = new Array();
        let dataModel = new Object();
        let warningInfoFacWor = '';
        let indexFacWor = 1;
        let warningInfoName = '';
        let indexName = 1;
        let warningInfoStaDat = '';
        let indexStaDat = 1;
        let warningInfoEndDat = '';
        let indexEndDat = 1;
        $.each($("#dataForm").serializeArray(), function (_, kv) {
            if (kv.name === 'profFacWor') {
                if (kv.value === '') {
                    warningInfoFacWor += "第" + indexFacWor + "行、";
                    indexFacWor++
                }
            }
            if (kv.name === 'profName') {
                if (kv.value === '') {
                    warningInfoName += "第" + indexName + "行、";
                    indexName++
                }
            }
            if (kv.name === 'profStaDat') {
                if (kv.value === '') {
                    warningInfoStaDat += "第" + indexStaDat + "行、";
                    indexStaDat++
                }
            }
            if (kv.name === 'profEndDat') {
                if (kv.value === '') {
                    warningInfoEndDat += "第" + indexEndDat + "行、";
                    indexEndDat++
                }
            }
        });
        if (warningInfoFacWor.length > 0) {
            warningInfoFacWor = warningInfoFacWor.substring(0, warningInfoFacWor.length - 1);
            js.modal.warning("尊敬的用户，请填写" + warningInfoFacWor + "分配车间/组/人员列的内容！");
            return;
        }
        if (warningInfoName.length > 0) {
            warningInfoName = warningInfoName.substring(0, warningInfoName.length - 1);
            js.modal.warning("尊敬的用户，请填写" + warningInfoName + "工作列的内容！");
            return;
        }
        if (warningInfoStaDat.length > 0) {
            warningInfoStaDat = warningInfoStaDat.substring(0, warningInfoStaDat.length - 1);
            js.modal.warning("尊敬的用户，请填写" + warningInfoStaDat + "开始时间列的内容！");
            return;
        }
        if (warningInfoEndDat.length > 0) {
            warningInfoEndDat = warningInfoEndDat.substring(0, warningInfoEndDat.length - 1);
            js.modal.warning("尊敬的用户，请填写" + warningInfoEndDat + "结束时间列的内容！");
            return;
        }

        $.each($("#dataForm").serializeArray(), function (_, kv) {
            if (kv.name === 'profFacWor') {
                dataModel.profFacWor = kv.value;
            }
            if (kv.name === 'profProdNo') {
                dataModel.profProdNo = kv.value;
            }
            if (kv.name === 'profName') {
                dataModel.profName = kv.value;
            }
            if (kv.name === 'profStaDat') {
                if (kv.value != "") {
                    dataModel.profStaDat = kv.value;
                } else {
                    dataModel.profStaDat = null;
                }
            }
            if (kv.name === 'prpdPlaEndDat') {
                if (kv.value != "") {
                    dataModel.prpdPlaEndDat = kv.value;
                }
            }
            if (kv.name === 'profEndDat') {
                if (kv.value != "") {
                    dataModel.profEndDat = kv.value;
                }
            }
            if (kv.name === 'profRem') {
                if (kv.value != "") {
                    dataModel.profRem = kv.value;
                }
                if (dataModel.profFacWor != undefined) {
                    dataArray.push(dataModel);
                    dataModel = new Object();
                }
            }
        });
        if (dataArray.length > 0 && $("#profProdNo").val() != undefined && $("#profProdNo").val() != '') {
            js.modal.confirm('尊敬的用户，您确定要保存生产计划编辑吗？', function () {
                js.post({
                    url: ctx + 'task/facPlaEdiAndRet/save',
                    type: 'post',
                    traditional: true,            // 阻止深度序列化， 使参数可以使用数组
                    dataType: 'json',
                    contentType: "application/x-www-form-urlencoded",
                    data: {
                        prodFacListJson: JSON.stringify(dataArray)
                    },
                    async: true,                // 异步执行
                    success: function (result) {
                        if (result.type === web_status.SUCCESS) {
                            js.modal.success(result.msg);
                            window.opener.reloadTable();
                            window.open('', '_self');
                            window.close();
                        } else {
                            js.modal.warning(result.msg);
                        }
                    },
                    error: function () {
                        js.modal.fail();
                    }
                });
            });
        } else if (dataArray.length === 0) {
            js.modal.warning("尊敬的用户，请添加生产计划！");
            return;
        }else if ($("#profProdNo").val() != undefined || $("#profProdNo").val() != '') {
            js.modal.warning("尊敬的用户，请选择项目编号！");
            $("#profProdNo").focus();
            return;
        }
    }

    /**
     * 取消
     */
    function cancel() {
        window.opener.reloadTable();
        window.open('', '_self');
        window.close();
    }
</script>
</body>
</html>